/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package client.process;

import client.GlobalForm;
import java.io.File;
import java.util.HashMap;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author ifan
 */
public class ClientProcess implements Runnable{

    public ClientProcess(){
        
    }

    private void generateHashUser() {
        File f = new File(GlobalVar.userXMLPath);
        XMLHandler xml = new XMLHandler();
        if(f.exists()) {
            GlobalVar.hashUser = xml.readXMLUserToHash(GlobalVar.userXMLPath);
        } else {
            boolean success = (new File("D:/kurakura")).mkdir();
            xml.updateInfoUsertoXML(GlobalVar.hashUser);
        }
    }

    public int loginVerification(String userName, char[] password) {
        int verify = 0;
        RepoClient repo = new RepoClient();
        RepoClient.perintah = repo.genRequestLogin();
        while(RepoClient.is==null) {
            
        }
        RepoClient.perintah = userName + " " + password.toString();
        try {
            if(RepoClient.is.readLine()=="1") {
    //        if(true) {
                GlobalVar.username = userName;
                generateHashUser();
                if(GlobalVar.hashUser.get(userName)!=null) {
                    verify = 2;
                } else {
                    verify = 1;
                }
            } else {
                
            }
        }
        catch (Exception ex) {

        }

        return verify;
    }

    public HashMap<String, Integer> compareHash(HashMap<String, InfoFile> hash1, HashMap<String, InfoFile> hash2) {
        HashMap<String, Integer> result = new HashMap<String, Integer>();
        // cek deleted file dan updated file
        for(String s1:hash1.keySet()) {
            InfoFile info1 = new InfoFile();
            InfoFile info2 = new InfoFile();
            info1 = hash1.get(s1);
            info2 = hash2.get(s1);
            if(info1!=null && info2==null) {
                result.put(s1, 1);
            } else if(info1.timestamp < info2.timestamp && info1.type!=0) {
                result.put(s1, 0);
            }
        }
        // cek new file
        for(String s2:hash2.keySet()) {
            InfoFile info1 = new InfoFile();
            InfoFile info2 = new InfoFile();
            info1 = hash1.get(s2);
            info2 = hash2.get(s2);
            if(info2!=null && info1==null) {
                result.put(s2, 0);
            }
        }
        return result;
    }

    public void synchronizeClientServer(String xmlServer, HashMap<String, InfoFile> oldHashClient) throws InterruptedException {
        HashMap<String, Integer> actionHash = new HashMap<String, Integer>();

        String xmlPath = GlobalVar.hashUser.get(GlobalVar.username).repositoryPath;
        long interval = (long) GlobalVar.hashUser.get(GlobalVar.username).interval;
        XMLHandler xmlHandler = new XMLHandler();
//        HashMap<String, InfoFile> oldHashClient = new HashMap<String, InfoFile>();
//        oldHashClient = xmlHandler.readXMLToHash(xmlPath);
//        Thread.sleep(interval*1000);
        int clientVersion = GlobalVar.clientVersion;
        HashMap<String, InfoFile> hashServer = new HashMap<String, InfoFile>();
        hashServer = xmlHandler.stringXMLToHash(xmlServer);
        int serverVersion = GlobalVar.serverVersion;
        if(clientVersion>=serverVersion) {
            // client commit
            HashMap<String, InfoFile> newHashClient = new HashMap<String, InfoFile>();
            newHashClient = xmlHandler.readXMLToHash(xmlPath);
            actionHash = compareHash(oldHashClient, newHashClient);
            GlobalVar.serverVersion++;
            GlobalVar.clientVersion = GlobalVar.serverVersion;
            // sini uplot file client ke server berdasarkan actionhash
            // kirim file xml ke server
        } else {
            // client update
            actionHash = compareHash(oldHashClient, hashServer);
            GlobalVar.clientVersion = GlobalVar.serverVersion;
            // sini donlot file server ke client berdasarkan actionHash
            // terus bikin ulang file xmlnya
            xmlHandler.updateInfoPathToXML(xmlPath);

            HashMap<String, InfoFile> newHashClient = new HashMap<String, InfoFile>();
            newHashClient = xmlHandler.readXMLToHash(xmlPath);
            actionHash = compareHash(oldHashClient, newHashClient);
            GlobalVar.serverVersion++;
            GlobalVar.clientVersion = GlobalVar.serverVersion;
            // kirim file xml ke server
            // sini uplodt file client ke server berdasarkan actionHash
        }
    }

    public void run() {
        while(GlobalVar.loop) {
            try {
                String xmlPath = GlobalVar.hashUser.get(GlobalVar.username).repositoryPath;
                long interval = (long) GlobalVar.hashUser.get(GlobalVar.username).interval;
                System.out.println("Tunggu " + Long.toString(interval) + " detik ya..");
                XMLHandler xmlHandler = new XMLHandler();
                HashMap<String, InfoFile> oldHashClient = new HashMap<String, InfoFile>();
                oldHashClient = xmlHandler.readXMLToHash(xmlPath);
                if(interval==0) {
                    Thread.sleep(30);
                } else {
                    Thread.sleep(interval*1000);
                }
                System.out.println("Udah " + Long.toString(interval) + " detik gannn... :D");
                synchronizeClientServer("", oldHashClient);
            } catch (InterruptedException ex) {
                Logger.getLogger(ClientProcess.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
        System.out.println("yeeeee...fiiinnnn");
    }


}
